<template>
	<div class="editor-container">
		<div :id="id"></div>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, ref, getCurrentInstance } from 'vue';
import { ElLoading } from 'element-plus';
import wangeditor from 'wangeditor';

import uploadCos from '/@/utils/uploadCos';
import { randomString } from '/@/utils/utils';

export default {
	name: 'wngEditor',
	props: {
		// 上传图片到服务器
		uploadImgUrl: {
			type: String,
			default: () => `${import.meta.env.VITE_API_URL}/admin/upload_gooods_details`,
		},
		// 节点 id
		id: {
			type: String,
			default: () => 'wangeditor',
		},
		// 是否禁用
		isDisable: {
			type: Boolean,
			default: () => false,
		},
		// 双向绑定
		// 双向绑定值，字段名为固定，改了之后将不生效
		// 参考：https://v3.cn.vuejs.org/guide/migration/v-model.html#%E8%BF%81%E7%A7%BB%E7%AD%96%E7%95%A5
		modelValue: String,
	},
	setup(props: { id: string; modelValue: any; isDisable: any; }, { emit }: any) {
		const state: any = reactive({
			editor: null,
		});
		const { proxy } = getCurrentInstance() as any;
		const loadingRef = ref(null);
		// 初始化富文本
		// https://doc.wangeditor.com/
		const initWangeditor = () => {
			state.editor = new wangeditor('#' + props.id);
			state.editor.config.menus = [
				'head', // 标题
				'bold', // 粗体
				'fontSize', // 字号
				'fontName', // 字体
				'italic', // 斜体
				'underline', // 下划线
				'strikeThrough', // 删除线
				'foreColor', // 文字颜色
				'backColor', // 背景颜色
				'justify', // 对齐方式
				'quote', // 引用
				'emoticon', // 表情
				'image', // 插入图片
				'undo', // 撤销
				'redo', // 重复
			];
			state.editor.config.placeholder = '请输入内容';
			state.editor.config.uploadImgShowBase64 = false;
			// state.editor.config.uploadImgServer = props.uploadImgUrl;
			state.editor.config.uploadImgMaxSize = 5 * 1024 * 1024;
			// state.editor.config.uploadFileName = 'file';
			// state.editor.config.uploadImgTimeout = 5000;
			// state.editor.config.uploadImgHeaders = {
			// 	token: Session.get('token'),
			// };
			state.editor.config.uploadImgMaxLength = 10;
			// state.editor.config.uploadImgHooks = {
			// 	before: () => {
			// 		(loadingRef.value as any) = ElLoading.service({
			// 			lock: true,
			// 			text: '上传中',
			// 			background: 'rgba(0, 0, 0, 0.7)',
			// 		});
			// 	},
			// 	success: () => {
			// 		(loadingRef.value as any)?.close();
			// 	},
			// 	fail: () => {
			// 		(loadingRef.value as any)?.close();
			// 	},
			// 	error: () => {
			// 		(loadingRef.value as any)?.close();
			// 	},
			// 	timeout: () => {
			// 		(loadingRef.value as any)?.close();
			// 	},

			// 	// 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
			// 	// （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
			// 	customInsert: (insertImg: any, result: any) => {
			// 		(loadingRef.value as any)?.close();
			// 		var url = result.data.info.show_url;
			// 		insertImg(url);
			// 	},
			// };

			state.editor.config.customUploadImg = (resultFiles: any, insertImgFn: any) => {
				(loadingRef.value as any) = ElLoading.service({
					lock: true,
					text: '上传中',
					background: 'rgba(0, 0, 0, 0.7)',
				});
				console.log('cos安达市', resultFiles);
				for (let index = 0; index < resultFiles.length; index++) {
					let fileExtension = resultFiles[index].name.substring(resultFiles[index].name.lastIndexOf('.') + 1);
					let path = `/hbsk_cloud/goods/details/${proxy.dayjs().year()}/${proxy.dayjs().month()}/${proxy.dayjs().date()}/${randomString(
						32
					).toLowerCase()}.${fileExtension}`;
					uploadCos(resultFiles[index], path)
						.then((res1: any) => {
							if (res1.url) {
								insertImgFn(res1.url);
								index + 1 == resultFiles.length && (loadingRef.value as any)?.close();
							} else {
								(loadingRef.value as any)?.close();
							}
						})
						.catch(() => {
							(loadingRef.value as any)?.close();
						});
				}
			};
			state.editor.config.showLinkImg = false;
			onWangeditorChange();
			state.editor.create();
			state.editor.txt.html(props.modelValue);
			props.isDisable ? state.editor.disable() : state.editor.enable();
		};
		// 销毁富文本
		const destroyWangeditor = () => {
			state.editor.destroy();
		};
		// 内容改变时
		const onWangeditorChange = () => {
			state.editor.config.onchange = (html: string) => {
				emit('update:modelValue', html);
			};
		};
		// // 页面加载时
		// onMounted(() => {
		// 	initWangeditor();
		// });
		return {
			initWangeditor,
			destroyWangeditor,
			...toRefs(state),
		};
	},
};
</script>

<style lang="scss">
.editor-container {
	.w-e-text-container {
		min-height: 500px;
		height: auto !important;
	}
}
</style>
